package com.gudaomai.ekproject.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.Page;
import com.gudaomai.ekproject.mapper.PageMapper;
import com.gudaomai.ekproject.service.IPageService;
import com.gudaomai.ekproject.service.impl.BaseServiceImpl;
import com.gudaomai.ekproject.web.PageController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 页面 服务实现类
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@Service
public class PageServiceImpl extends BaseServiceImpl<PageMapper, Page> implements IPageService {

	@Autowired
	MessageSource messageSource;

	// 通过page名称检测数据库是否存在page
	@Override
	public boolean isExist(String pageName) {

		EntityWrapper<Page> ew=new EntityWrapper<>();
		ew.setEntity(new Page());
		ew.eq("name", pageName);
		Page page=this.selectOne(ew);
		
//		Page page = this.baseMapper.getPageByName(pageName);

		if (page == null) {
			return false;
		}
		return true;
	}

	// 获取页面顺序的最大值，为从而为新加入的页面赋值
	/**
	 * {@link PageMapper}
	 * 
	 * @see PageController.addPage
	 */
	@Override
	public int getSortOrder(String projectId) {

		// 若当前数据库不存在记录order==null，则直接返回0
		Object order = this.baseMapper.getMaxOrder(projectId);

		if (order == null) {
			return 0;
		}
		// 返回页面顺序的最大值
		return (int) order;
	}

	// 通过id获取当前页面的信息
	@Override
	public Page getPageById(String pageId) throws CommonException {

		// 因为是从页面直接获取，除数据在被访问时删除外，均能查询到该记录
		Page page = this.selectById(pageId);

		if (page != null) {
			return page;
		} else {
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_FOUND,
					getMessage(MsgConstant.RET_PAGE_SELECT_NOTEXIST));
		}

	}

	// 获取同级上一个页面
	@Override
	public Page getUpPageById(String pageId) throws CommonException {

		Page page = this.baseMapper.getLastPage(pageId);

		if (page != null) {
			return page;
		} else {
			// 如果当前页面是第一条,则抛出异常
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PAGE_MOVE_UP_FAILURE));
		}
	}

	// 获取同级下一个页面
	@Override
	public Page getDownPageById(String pageId) throws CommonException {

		Page page = this.baseMapper.getNextPage(pageId);
		if (page != null) {
			return page;
		} else {
			// 如果当前页面是最后一条,则抛出异常
			throw new CommonException(CommonConstant.RESULT_CODE_NOT_MODIFIED,
					getMessage(MsgConstant.RET_PAGE_MOVE_DOWN_FAILURE));
		}
	}

}
